﻿Imports Microsoft.VisualBasic
Imports Microsoft.VisualBasic.FileIO
Imports System.IO
Imports JPC.Medialibrary.DAL
Imports System.Globalization

Namespace JPC.Medialibrary.UI

    Public Class FilesMenu
        Inherits List(Of ListItem)

        Sub New(ByVal DirectoryPath As String, ByVal MenuType As String)
            'Dim i As ListItem

            If DirectoryPath = "" Then
                'i = New ListItem
                'i.CommandName = "Inicio"
                'i.CommandArgument = ""
                'i.Info = ""
                'i.Text = "<<< Volver al Menú de Inicio"
                'Me.Add(i)
                Select Case MenuType
                    Case "Series"
                        InspectForSeries()
                    Case "CDROM"
                        InspectCDROM()
                End Select
            Else
                'i = New ListItem
                'i.CommandName = "InspectDirectory"
                'i.CommandArgument = ""
                'i.Info = ""
                'i.Text = "<<< Volver a la Lista de Series"
                'Me.Add(i)
                InspectDirectory(DirectoryPath, MenuType)
            End If

        End Sub

        Private Sub InspectForSeries()

            'Busca en todos los discos del sistema
            For Each drive As DriveInfo In My.Computer.FileSystem.Drives
                'Busca si existe una carpeta Medialibrary
                If drive.DriveType = DriveType.Fixed Then
                    If My.Computer.FileSystem.DirectoryExists(drive.Name + "Medialibrary\Series") Then
                        InspectDirectory(drive.Name + "Medialibrary\Series", "Series")
                    End If
                End If
            Next

        End Sub

        Public Shared Function IsDVD() As Boolean

            Dim blnIsDVD As Boolean = False
            For Each drive As DriveInfo In My.Computer.FileSystem.Drives
                If drive.DriveType = DriveType.CDRom Then
                    If drive.IsReady Then
                        For Each Dir As String In My.Computer.FileSystem.GetDirectories(drive.Name)
                            Dim dirInfo As New DirectoryInfo(Dir)
                            If dirInfo.Name = "VIDEO_TS" Then
                                blnIsDVD = True
                                Exit For
                            End If
                        Next
                    End If
                    Exit For
                End If
            Next

            Return blnIsDVD

        End Function

        Private Sub InspectCDROM()

            'Busca en el CDROM
            For Each drive As DriveInfo In My.Computer.FileSystem.Drives
                If drive.DriveType = DriveType.CDRom Then
                    ''Espera 5 segundos a que el cd esté listo
                    'For i As Integer = 1 To 5
                    '    If drive.IsReady Then Exit For
                    '    System.Threading.Thread.Sleep(1000)
                    'Next
                    If drive.IsReady Then
                        InspectDirectory(drive.Name, "CDROM")
                    Else
                        Dim i As ListItem
                        i = New ListItem
                        i.CommandName = "InspectDirectory"
                        i.CommandArgument = ""
                        i.Info = ""
                        i.Text = "Inserte un CD-ROM y vuelva a intentarlo"
                        Me.Add(i)
                    End If
                    Exit For
                End If
            Next

        End Sub

        Private Sub InspectDirectory(ByVal dirPath As String, ByVal MenuType As String)
            Dim i As ListItem

            Dim wildCard() As String = {"*.*"}

            Select Case MenuType
                Case "Series"
                    wildCard = New String() {"*.avi"}
                Case "CDROM"
                    wildCard = New String() {"*.cda", "*.mp3", "*.wma", "*.wav", "*.avi", "*.mpg", "*.mpeg", "*.mov", "*.wmv", "*.jpg", "*.jpeg", "*.gif", "*.bmp"}
            End Select

            'Primero carga todos los archivos de la carpeta
            For Each file As String In My.Computer.FileSystem.GetFiles(dirPath, FileIO.SearchOption.SearchTopLevelOnly, wildCard)
                i = New ListItem
                Dim fileInfo As New FileInfo(file)
                Select Case fileInfo.Extension
                    Case ".avi", ".wmv", ".mpg", ".mpeg", ".mov"
                        i.CommandName = "PlayVideo"
                        If MenuType = "Series" Then
                            i.Text = GetEpisodeName(file)
                            i.Info = GetEpisodeDateViewed(file)
                        Else
                            i.Text = fileInfo.Name
                            i.ObjectType = "Video"
                        End If
                    Case ".cda", ".mp3", ".wma", ".wav"
                        i.CommandName = "PlayAudio"
                        i.Text = fileInfo.Name
                        i.ObjectType = "Audio"
                    Case Else
                        i.Text = fileInfo.Name
                End Select
                i.CommandArgument = file
                Me.Add(i)
            Next

            'Después procesa las subcarpetas
            For Each Dir As String In My.Computer.FileSystem.GetDirectories(dirPath)
                i = New ListItem
                i.CommandName = "InspectDirectory"
                i.CommandArgument = Dir
                Dim dirInfo As New DirectoryInfo(Dir)
                If MenuType = "Series" Then
                    i.Text = GetSeriesName(Dir)
                    i.ThumbnailURL = GetSeriesThumbnail(Dir)
                    i.Info = "(" & CStr(GetNewEpisodesQty(Dir)) & ")&nbsp&nbsp"
                Else
                    i.Text = dirInfo.Name
                    i.ObjectType = "Folder"
                End If
                Me.Add(i)
            Next

        End Sub

        Private Function GetEpisodeName(ByVal file As String) As String
            Dim fileInfo As New FileInfo(file)
            Dim dirInfo As DirectoryInfo = fileInfo.Directory
            Dim fileName As String
            Dim dirName As String

            fileName = StrConv(fileInfo.Name.Replace(".", " ").Replace("-", " "), VbStrConv.ProperCase)
            dirName = StrConv(dirInfo.Name, VbStrConv.ProperCase)

            If InStr(dirName, " - ") <> 0 Then
                dirName = Mid(dirName, 1, InStr(dirName, " - ")).Trim
            End If

            If InStr(fileName, dirName) <> 0 Then
                fileName = Mid(fileName, Len(dirName) + 1).Trim
            End If

            fileName = Mid(fileName, 1, fileName.Length - 4)

            'Formato S01E01
            If Mid(fileName, 1, 1).ToUpper = "S" And IsNumeric(Mid(fileName, 2, 2)) And _
                Mid(fileName, 4, 1).ToUpper = "E" And IsNumeric(Mid(fileName, 5, 2)) Then

                If Mid(fileName, 7).Trim = "" Then
                    fileName = "Episodio " + Mid(fileName, 5, 2)
                Else
                    fileName = "Ep." + Mid(fileName, 5, 2) + " - " + Mid(fileName, 7).Trim
                End If

                'Formato 1X01
            ElseIf IsNumeric(Mid(fileName, 1, 1)) And Mid(fileName, 2, 1).ToUpper = "X" And _
                IsNumeric(Mid(fileName, 3, 2)) Then
                fileName = "Ep." + Mid(fileName, 3, 2) + " - " + Mid(fileName, 5).Trim

                'Formato 01X01
            ElseIf IsNumeric(Mid(fileName, 1, 2)) And Mid(fileName, 3, 1).ToUpper = "X" And _
                IsNumeric(Mid(fileName, 4, 2)) Then
                fileName = "Ep." + Mid(fileName, 4, 2) + " - " + Mid(fileName, 6).Trim

            End If
            Return fileName

        End Function

        Private Function GetSeriesName(ByVal Dir As String) As String
            Dim dirInfo As New DirectoryInfo(Dir)
            Return dirInfo.Name
        End Function

        Private Function GetSeriesThumbnail(ByVal Dir As String) As String
            Dim thumbFileName As String = "~\Images\Video_Thumbnail.jpg"

            If My.Computer.FileSystem.FileExists(Dir & "\Thumb.jpg") Then
                thumbFileName = Dir & "\Thumb.jpg"
            End If

            Return thumbFileName
        End Function

        Private Function GetNewEpisodesQty(ByVal dir As String) As Integer

            Dim ep As New Episodios
            ep.EpisodiosVistos = 0
            ep.TotalEpisodios = 0
            GetTotalEpisodesQty(dir, ep)

            'Return ep.TotalEpisodios - ep.EpisodiosVistos & "/" & ep.TotalEpisodios & "&nbsp&nbsp"
            Return ep.TotalEpisodios - ep.EpisodiosVistos

        End Function

        Private Function GetEpisodeDateViewed(ByVal filename As String) As String
            Dim fileInfo As String = ""

            Dim _episode As New EpisodeViewHistory
            _episode.LoadByParam(EpisodeViewHistory.Columns.FileName, filename)
            If Not _episode.IsNew Then
                fileInfo = CDate(_episode.ViewDate).ToString("dd MMM", New CultureInfo("es-ES"))
                fileInfo = StrConv(fileInfo, VbStrConv.ProperCase) & "&nbsp&nbsp"
            End If

            Return fileInfo

        End Function

        Private Sub GetTotalEpisodesQty(ByVal Dir As String, ByVal ep As Episodios)

            For Each File As String In My.Computer.FileSystem.GetFiles(Dir, FileIO.SearchOption.SearchTopLevelOnly, "*.avi")
                ep.TotalEpisodios += 1
                Dim _episode As New EpisodeViewHistory
                _episode.LoadByParam(EpisodeViewHistory.Columns.FileName, File)
                If Not _episode.IsNew Then
                    ep.EpisodiosVistos += 1
                End If
            Next

            For Each SubDir As String In My.Computer.FileSystem.GetDirectories(Dir)
                GetTotalEpisodesQty(SubDir, ep)
            Next

        End Sub

    End Class

    Public Class Episodios
        Public TotalEpisodios As Integer
        Public EpisodiosVistos As Integer

    End Class

End Namespace